package com.demo.config;

import com.demo.properties.EmailProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author wangfengchen
 * prefix为配置文件中的前缀
 * name为配置的名字
 * havingValue是与配置的值对比值,当两个值相同返回true,配置类生效
 */
@Configuration
@EnableConfigurationProperties(EmailProperties.class)
@ConditionalOnProperty(prefix = "email", name = "enabled", havingValue = "true")
public class EmailAutoConfiguration {

  @Autowired(required = false)
  private EmailProperties emailProperties;

  @Bean
  @Primary
  @ConditionalOnMissingBean
  public JavaMailSenderImpl buildEmailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(emailProperties.getHost());
    mailSender.setUsername(emailProperties.getUsername());
    mailSender.setPassword(emailProperties.getPassword());
    mailSender.setDefaultEncoding(StandardCharsets.UTF_8.toString());
    // 加认证机制
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.ssl.enable", "true");
    // 防止文件名过长错误ATTxx.bin进行全局定义
    properties.setProperty("mail.mime.splitlongparameters", "false");
    properties.setProperty("mail.smtp.socketFactory.port", "465");
    properties.setProperty("mail.smtp.socketFactory.fallback", "false");
    properties.setProperty("mail.smtp.socketFactory.class",
        "javax.net.ssl.SSLSocketFactory");
    mailSender.setJavaMailProperties(properties);
    return mailSender;
  }

}